package com.logistic.server.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * cookie操作类
 */
public class CookieUtil {

    /**
     * 设置Cookie
     * @param response 响应对象
     * @param name 键
     * @param value 值
     * @param maxAge 时间
     */
    public static void set(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 获取Cookie
     * @param request 请求对象
     * @param name 键
     * @return str
     */
    public static String get(HttpServletRequest request, String name) {
        Map<String, Cookie> map = readCookieMap(request);
        if (map.containsKey(name)) {
            return map.get(name).getValue();
        } else{
            // cookies 中没有 取头中信息
            return request.getHeader(name);
        }
    }

    /**
     * 将cookie封装成map
     * @param request 请求对象
     * @return str
     */
    private static Map<String,Cookie> readCookieMap(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        Map<String,Cookie> map = new HashMap<>();
        if(cookies != null){
            for(Cookie cookie : cookies){
                map.put(cookie.getName(),cookie);
            }
        }
        return map;
    }
}
